# -*- coding: UTF-8 -*-

import re
import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['PromAlarmMetrics']

class PromAlarmMetrics(Base, SessionMixin):
    '''
    告警指标
    '''
    __tablename__ = "prom_alarm_metrics"
    name = Column(String(256), nullable=False, comment='指标名称')
    # ECS服务器 or k8s容器
    classes = Column(String(128), nullable=False, index=True, comment='指标归类')
    # record(记录规则) or alarm(告警规则)
    type = Column(String(16), nullable=False, comment='规则类型')
    expr = Column(TEXT, nullable=False, comment='指标表达式')
    # 是否有操作符
    has_operator = Column(Boolean, default=text('True'), nullable=False, comment='是否有操作符')
    # 数组 list
    parameters = Column(JSON, nullable=False, default=[], comment='参数列表')
    # 字典 dict
    annotations = Column(JSON, nullable=False, default={}, comment='附加信息')
    comment = Column(String(256), nullable=True, comment='指标说明')



    __table_args__ = (
        Index('idx_prom_alarm_metrics_name', 'name', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<prom_alarm_metrics='{self.name}>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }
        return result


    @classmethod
    def convert_host_expr(cls, expr: str, host_name: str):
        expr = expr.replace("{host_name}", host_name)
        return expr


    @classmethod
    def convert_expr(cls, db: Session, uuid: int, parameter_info: dict):
        """
        告警指标转换成prometheus告警规则的表达式
        """
        alarm_metrics_info = cls.get_object_info_by_uuid(db, uuid)
        expr = alarm_metrics_info["expr"]
        # 更新参数
        for parameter in alarm_metrics_info["parameters"]:
            old_str = f"{parameter}"
            new_str = ""
            if parameter in parameter_info and parameter_info[parameter]:
                new_str = parameter + f"\"{parameter_info[parameter]}\""

            expr = expr.replace(old_str, new_str)

        # 去除空格
        # expr = expr.replace(" ", "")
        # 中间多个,号 改成一个,号
        expr = re.sub(",+", ",", expr)
        # 去除前面多余的,号
        expr = expr.replace("{,", "{")
        # 去除后面面多余的,号
        expr = expr.replace(",}", "}")
        return expr




